package com.gzh.core.chche.service;

import com.alibaba.fastjson.JSONObject;
import com.gzh.core.chche.dao.mapper.TshoolMapper;
import com.gzh.core.chche.dao.po.TschoolEntityCache;
import com.gzh.core.chche.service.dto.School;
import com.gzh.core.chche.dao.po.TschoolBeanCache;
import com.gzh.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author guanzh
 * @Date 2022/1/4 14:52
 * @Description
 */
@Service
public class SchoolCache extends Cache<School> {
    @Autowired
    private TshoolMapper tschoolMapper;

    public SchoolCache() {
        this.cacheKey = "school";
        this.cacheName = "学校信息";
    }

    @Override
    public Map<String, String> loadCacheData(List<String> keyList, String updateTime) {
        TschoolBeanCache tschoolBeanCache = new TschoolBeanCache();
        tschoolBeanCache.setSchoolIdList(keyList);
        List<TschoolEntityCache> schoolList = tschoolMapper.queryTschool(tschoolBeanCache);
        Map<String, String> map = new LinkedHashMap<>();
        for (TschoolEntityCache item : schoolList) {
            School bond = new School(item);
            map.put(getKey(bond), JSONObject.toJSONString(bond));
        }
        return map;
    }

    @Override
    public List<School> getObjectListByKeyword(String findstr) {
        List<School> resultList = new ArrayList<>();
        List<School> allList = this.getAllList();
        for (School school : allList) {
            if (school != null &&(StringUtils.toString(school.getSchoolId()).contains(findstr) ||
                    school.getSchoolName().contains(findstr) || school.getSchoolCode().contains(findstr))){
                resultList.add(school);
            }
        }
        resultList = resultList.stream().sorted(Comparator.comparing(School::getSchoolId)).collect(Collectors.toList());
        return resultList;
    }

    @Override
    public String getKey(School school) {
        if (school == null) {
            return "";
        }
        return String.valueOf(school.getSchoolId());
    }

}
